package com.xindaoapp.happypet.ui;

import java.util.Map;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.DrawerLayout;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.ActivityNearFriend;
import com.xindaoapp.happypet.activity.InviteActivity;
import com.xindaoapp.happypet.activity.MyLoveActivity;
import com.xindaoapp.happypet.activity.MyOrderListActivity;
import com.xindaoapp.happypet.activity.MyPostActivity;
import com.xindaoapp.happypet.activity.SettingActivity;
import com.xindaoapp.happypet.bean.MyMessageInfo;
import com.xindaoapp.happypet.bean.User;
import com.xindaoapp.happypet.fragments.MyInfoFragment;
import com.xindaoapp.happypet.protocol.MoccaApi;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.Constants.NoticeLabel;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.ProgressHUD;

/**
 * 个人中心
 * 
 * @author chenghao
 * 
 */
public class PersonalCenterFragment_new extends BaseFragment implements OnClickListener {



    public PersonalCenterFragment_new() {
        super();
    }

    /** 消息推送底部tab红点标记 */
    private View vNoticeMessageLabelIcon;
    private NoticeReceiver mNoticeReceiver;
    private ReceiveJpush mReceiveJpush;

    /** 登录按钮 */
    private View vLogin;
    /** 用户名 */
    private TextView vUserName, tv_niubi;
    /** 用户头像 */
    private ImageView vUserIcon, bt_message;
    private Button bt_qiandao;

    private LoginSuccessReceiver mLoginSuccessReceiver;
    private WeiBaCountChangedReceiver mWeiBaCountChangedReceiver;
    private ChangeImgOKReceiver mChangeImgOKReceiver;

    private SharedPreferences sp;

    // UserState.getUser().niuniu

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.layout_personal_center_new, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 个人中心禁用左侧滑动
        DrawerLayout mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
        // mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        mReceiveJpush = new ReceiveJpush();
        getActivity().registerReceiver(mReceiveJpush,
                new IntentFilter(Constants.ACTION_RECEIVED_NOTICE));
        mNoticeReceiver = new NoticeReceiver();
        mLoginSuccessReceiver = new LoginSuccessReceiver();
        mWeiBaCountChangedReceiver = new WeiBaCountChangedReceiver();
        mChangeImgOKReceiver = new ChangeImgOKReceiver();
        getActivity().registerReceiver(mChangeImgOKReceiver, new IntentFilter(Constants.KEY_ACTID));

        getActivity().registerReceiver(mNoticeReceiver,
                new IntentFilter(Constants.KEY_NOTICE_STATE_CHANGED));
        getActivity().registerReceiver(mLoginSuccessReceiver,
                new IntentFilter(Constants.ACTION_LOGIN_STATE_CHANGED));
        getActivity().registerReceiver(mWeiBaCountChangedReceiver,
                new IntentFilter(Constants.ACTION_WEIBA_COUNT_CHANGED));
        issingn();
        setUserInfos();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiveJpush);
        getActivity().unregisterReceiver(mNoticeReceiver);
        getActivity().unregisterReceiver(mLoginSuccessReceiver);
        getActivity().unregisterReceiver(mWeiBaCountChangedReceiver);
        getActivity().unregisterReceiver(mChangeImgOKReceiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        // setUserInfos();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected void initViews() {
        super.initViews();
        // initTopBg(view);
        vNoticeMessageLabelIcon = mView.findViewById(R.id.iv_push);
        sp = mContext.getSharedPreferences("userconfig", Context.MODE_PRIVATE);
        vLogin = mView.findViewById(R.id.login);
        vUserName = (TextView) mView.findViewById(R.id.user_name);
        vUserIcon = (ImageView) mView.findViewById(R.id.user_icon);
        bt_qiandao = (Button) mView.findViewById(R.id.bt_qiandao);
        bt_message = (ImageView) mView.findViewById(R.id.bt_message);
        tv_niubi = (TextView) mView.findViewById(R.id.tv_niubi);
        tv_niubi.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        bt_qiandao.setText("签到");
        if (UserState.getUser() != null) {
            issingn();
            setUserInfos();
        } else {
            bt_qiandao.setVisibility(View.INVISIBLE);
        }

        getIsNew();

    }

    private void getIsNew() {
        // TODO Auto-generated method stub
        getMoccaApi().getMyMessageInfo(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<MyMessageInfo>() {

                    @Override
                    public void request(MyMessageInfo t) {

                        if (t != null) {
                            if (Integer.parseInt(t.getIsnew().trim()) > 0) {
                                Constants.NoticeLabel.sHasNewMessageNotice = true;
                                // vNoticeMessageLabelIcon.setVisibility(View.VISIBLE);
                            } else {
                                Constants.NoticeLabel.sHasNewMessageNotice = false;
                                // vNoticeMessageLabelIcon.setVisibility(View.GONE);
                            }
                            mContext.sendBroadcast(new Intent(Constants.KEY_NOTICE_STATE_CHANGED));

                        }
                    }
                });

    }

    @Override
    protected void initEvents() {
        super.initEvents();
        vUserIcon.setOnClickListener(this);
        bt_qiandao.setOnClickListener(this);
        bt_message.setOnClickListener(this);
        vLogin.setOnClickListener(this);
        tv_niubi.setOnClickListener(this);
        // mView.findViewById(R.id.r_top).setOnClickListener(this);
        mView.findViewById(R.id.r_mytop).setOnClickListener(this);
        mView.findViewById(R.id.setting).setOnClickListener(this);
        mView.findViewById(R.id.tab_invitation).setOnClickListener(this);
        // mView.findViewById(R.id.tab_attention).setOnClickListener(this);
        mView.findViewById(R.id.tab_fans).setOnClickListener(this);
        mView.findViewById(R.id.tab_chongyou).setOnClickListener(this);
        mView.findViewById(R.id.tab_mylove).setOnClickListener(this);
        mView.findViewById(R.id.tab_mycollect).setOnClickListener(this);
        // mView.findViewById(R.id.tab_mymessage).setOnClickListener(this);
        // mView.findViewById(R.id.tab_myorder).setOnClickListener(this);
        // mView.findViewById(R.id.tab_mygoods).setOnClickListener(this);
        mView.findViewById(R.id.tab_myshipping_address).setOnClickListener(this);
        mView.findViewById(R.id.tab_myorderList).setOnClickListener(this);
        mView.findViewById(R.id.invite_friend).setOnClickListener(this);
        mView.findViewById(R.id.tab_weibaduihuan).setOnClickListener(this);
    }

    /**
     * 
     */
    private void initTopBg(View view) {
        LayoutParams params =
                new LayoutParams(CommonParameter.sScreenWidth,
                        CommonParameter.sScreenWidth * 327 / 640);
        view.findViewById(R.id.r_top).setLayoutParams(params);
    }

    private void setUserInfos() {
        if (UserState.isLogged()) {
            bt_qiandao.setVisibility(View.VISIBLE);
            bt_message.setVisibility(View.VISIBLE);
            tv_niubi.setText(UserState.getUser().niuniu + "尾巴币");
            tv_niubi.setVisibility(View.VISIBLE);
            vLogin.setVisibility(View.GONE);
            vUserName.setVisibility(View.VISIBLE);
            vUserIcon.setVisibility(View.VISIBLE);
            vUserName.setText(UserState.getUser().username);
            String userIcon = UserState.getUser().userface;
            // ImageLoader.getInstance().clearMemoryCache();
            // ImageLoader.getInstance().clearDiscCache();
            // DisplayImageOptions options =
            // new DisplayImageOptions.Builder().cacheInMemory(false).cacheOnDisc(false)
            // .build();
            ImageLoader.getInstance().displayImage(UserState.getUser().userface, vUserIcon);
            // BitmapHelp.getBitmapUtils(mContext).display(vUserIcon, userIcon);
            // String issign = UserState.getUser().issign;
            // if ("1".equals(issign)) {
            // bt_qiandao.setText("已签到");
            // } else {
            // bt_qiandao.setText("签到");
            // }
        } else {
            vLogin.setVisibility(View.VISIBLE);
            vUserName.setVisibility(View.GONE);
            vUserIcon.setVisibility(View.GONE);
            tv_niubi.setVisibility(View.GONE);
            bt_qiandao.setVisibility(View.GONE);
            bt_message.setVisibility(View.GONE);
            vNoticeMessageLabelIcon.setVisibility(View.GONE);



        }
    }

    private void popDialog() {
        Button btnItem1;
        /* 初始化普通对话框。并设置样式 */
        final Dialog selectDialog = new Dialog(getActivity(), R.style.custom_dialog);
        selectDialog.setCancelable(true);
        /* 设置普通对话框的布局 */
        selectDialog.setContentView(R.layout.layout_custom_dialog);

        Window dialogWindow = selectDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        // lp.x = 80; // 新位置X坐标
        lp.y = 100; // 新位置Y坐标
        // lp.width = 300; // 宽度
        // lp.height = 250; // 高度
        // lp.alpha = 0.9f; // 透明度

        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);

        btnItem1 = (Button) selectDialog.findViewById(R.id.button1);
        btnItem1.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectDialog.dismiss();// 隐藏对话框
            }
        });
        selectDialog.show();// 显示对话框
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
        // case R.id.r_top:
            case R.id.user_icon:
                if (UserState.isLogged(getActivity())) {
                    intent.setClass(getActivity(),
                            com.xindaoapp.happypet.activity.MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            MyInfoFragment.class.getCanonicalName());
                    startActivity(intent);
                }
                break;
            case R.id.login:
                if (UserState.isLogged(getActivity())) {
                    // intent.setClass(getActivity(), MainActivity.class);
                    // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                    // LoginFragment.class.getCanonicalName());
                    // startActivity(intent);
                    intent.setClass(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.setting:
                intent.setClass(getActivity(), SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.tab_invitation:// 我的帖子
                if (UserState.isLogged(getActivity())) {
                    intent.setClass(getActivity(), MyPostActivity.class);
                    startActivity(intent);
                }
                break;
            // case R.id.tab_attention:
            // if (UserState.isLogged(getActivity())) {
            // intent.setClass(getActivity(), MenuAttention.class);
            // startActivity(intent);
            // }
            // break;
            case R.id.tab_fans:// 我的好友
                if (UserState.isLogged(getActivity())) {
                    intent.setClass(getActivity(), MyFriendActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tab_chongyou:// 附近的宠友
                // if (UserState.isLogged(getActivity())) {
                intent.setClass(getActivity(), ActivityNearFriend.class);
                startActivity(intent);
                // }
                break;
            case R.id.tab_mylove:// 我的爱
                if (UserState.isLogged(getActivity())) {
                    intent.setClass(getActivity(), MyLoveActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tab_mycollect:// 我的收藏
                if (UserState.isLogged(getActivity())) {
                    intent.setClass(getActivity(), MyCollectListActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.bt_qiandao:
                if (UserState.isLogged(getActivity())) {
                    if (bt_qiandao.getText().equals("已签到")) {
                        Intent qiandao = new Intent(getActivity(), QiandaoRecordActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isOK", true);
                        qiandao.putExtras(bundle);
                        startActivity(qiandao);
                    } else {
                        goToSign();
                    }
                }
                break;
            case R.id.tab_myshipping_address:
                if (UserState.isLogged(getActivity())) {
                    // intent.setClass(getActivity(), MainActivity.class);
                    // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                    // ConsigneeFragment.class.getCanonicalName());
                    // startActivity(intent);
                    intent.setClass(getActivity(), ConsigneeActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tab_myorderList:
                if (UserState.isLogged(getActivity())) {
                    startActivity(new Intent(getActivity(), MyOrderListActivity.class));
                }
                break;
            case R.id.tab_weibaduihuan:// 尾巴兑换
                if (UserState.isLogged(getActivity())) {
                    Intent inte = new Intent(getActivity(), ChangeCenterActivity.class);
                    startActivity(inte);
                }
                break;
            case R.id.tv_niubi:
                // intent.setClass(getActivity(), MainActivity.class);
                // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                // ChangeCenterFragment.class.getCanonicalName());
                // startActivity(intent);
                // intent.setClass(getActivity(), ChangeCenterActivity.class);
                // startActivity(intent);

                // Intent integral = new Intent(mContext, MainActivity.class);
                // Bundle bundle = new Bundle();
                // bundle.putBoolean("isPsersonal", true);
                // integral.putExtra(Constants.KEY_BUNDLE, bundle);
                // integral.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                // IntegralFragment.class.getCanonicalName());
                // mContext.startActivity(integral);

                Intent intent2 = new Intent(mContext, MyRecordActivity.class);
                intent2.putExtra("isPsersonal", true);
                mContext.startActivity(intent2);

                break;
            case R.id.bt_message:
                // startActivity(new Intent(getActivity(), MessageActivity.class));
                // vNoticeMessageLabelIcon.setVisibility(View.GONE);
                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                break;
            case R.id.invite_friend:// 邀请好友
                if (UserState.isLogged(getActivity())) {
                    startActivity(new Intent(getActivity(), InviteActivity.class));
                }
                break;
        }
    }

    class LoginSuccessReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            issingn();
            setUserInfos();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if (resultCode == Activity.RESULT_CANCELED) {
        // if (requestCode == 1) {
        // Bitmap decodeFile =
        // BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
        // .getAbsolutePath() + "/happypet/usericon/temp.jpg");
        // if (decodeFile != null) {
        // vUserIcon.setImageBitmap(decodeFile);
        // }
        // }
    }

    /** 签到 */
    private void goToSign() {
        // SimpleDateFormat sdf = new SimpleDateFormat("dd");
        // String date = UserState.getUserUid() + sdf.format(new java.util.Date());

        // if (!(UserState.getUserUid() + date).equals(sp.getString("date", null))) {
        final ProgressHUD dialog = ProgressHUD.show(mContext, "正在签到请稍候...", true, true, null);
        getMoccaApi().goToSign(new IRequest<Pair<Boolean, String>>() {
            @Override
            public void request(Pair<Boolean, String> t) {
                if (null == getActivity()) {
                    return;
                }
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (null != t) {
                    if (t.first) {

                        showDialog2(t.second);

                        CommonUtil.refurshWeiba(mContext);

                        bt_qiandao.setText("已签到");
                        // bt_qiandao.setClickable(false);
                        Intent intent = new Intent(getActivity(), QiandaoRecordActivity.class);
                        startActivity(intent);
                    } else {
                        bt_qiandao.setText("已签到");
                        Intent qiandao = new Intent(getActivity(), QiandaoRecordActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isOK", true);
                        qiandao.putExtras(bundle);
                        startActivity(qiandao);
                        // Toast.makeText(getActivity(), t.second, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getActivity(), getResources().getString(R.string.net_error),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void showDialog2(String str) {
        LayoutInflater inflater = getLayoutInflater(getArguments());
        View layout = inflater.inflate(R.layout.layout_sign_success, null);
        TextView tv_addscore = (TextView) layout.findViewById(R.id.tv_addscore);
        tv_addscore.setText(str);
        Toast toast = new Toast(mContext);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();

        // HappyPetApplication.mHandler.postDelayed(new Runnable() {
        //
        // @Override
        // public void run() {
        // // popDialog();
        // }
        // }, 3000);
    }


    private void issingn() {

        if (UserState.getUser() != null) {

            getMoccaApi().getUserInfoByUid(UserState.getUserUid(),
                    new IRequest<Map<String, Object>>() {

                        @Override
                        public void request(Map<String, Object> t) {
                            if (t != null) {
                                User user = (User) t.get(MoccaApi.RESPONSE_USERINFO);
                                String issign = user.issign;
                                if ("1".equals(issign)) {
                                    bt_qiandao.setText("已签到");
                                    // bt_qiandao.setClickable(false);
                                    // Intent intent = new
                                    // Intent(getActivity(),QiandaoRecordActivity.class);
                                    // startActivity(intent);
                                } else {
                                    bt_qiandao.setText("签到");
                                }
                            }
                        }
                    });
        }
    }

    class WeiBaCountChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            tv_niubi.setText(UserState.getUser().niuniu + "尾巴币");
        }

    }

    class NoticeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (NoticeLabel.sHasNewMessageNotice) {
                vNoticeMessageLabelIcon.setVisibility(View.VISIBLE);
            } else {
                vNoticeMessageLabelIcon.setVisibility(View.GONE);
            }
        }

    }
    class ReceiveJpush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            getIsNew();
        }

    }

    private class ChangeImgOKReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bitmap decodeFile =
                    BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/happypet/usericon/temp.jpg");
            if (decodeFile != null) {
                vUserIcon.setImageBitmap(decodeFile);
            }
        }
    }
}
